<?php
class User_AuthController extends Protox_Controller_Action
{
	public function indexAction() {

		$this->_helper->layout()->disableLayout();
		$this->_helper->layout()->setLayout('login');

		$form = new User_Form_Login();

		$request = $this->getRequest();
		if ($request->isPost()) {
			if ($form->isValid($request->getPost())) {
				if ($this->_process($form->getValues())) {
					$this->_helper->redirector('index', 'index','default');
				} else {
					$this->view->priorityMessenger('Ops, Falha na autenticação de usuário. Verifique seu usuário e senha.', 'error');
				}
			} else {
				$form->populate($this->getRequest()->getPost());
			}
		}
		$this->view->form = $form;
	}

	protected function _process($values)
	{
		// Get our authentication adapter and check credentials
		$adapter = $this->_getAuthAdapter();
		$adapter->setIdentity($values['username']);
		$adapter->setCredential(sha1($values['password']));

		$auth = Zend_Auth::getInstance();
		$result = $auth->authenticate($adapter);
		if ($result->isValid()) {
			$user = $adapter->getResultRowObject();
			$auth->getStorage()->write($user);
			return true;
		}
		return false;
	}

	protected function _getAuthAdapter() {

		$dbAdapter = Zend_Db_Table::getDefaultAdapter();
		$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);

		$authAdapter->setTableName('users')
		->setIdentityColumn('username')
		->setCredentialColumn('password');
			
		return $authAdapter;
	}

	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->_helper->redirector('index', 'auth');
	}


}